package com.sayimo.maker.mall.goods.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sayimo.framework.exception.DaoException;
import com.sayimo.framework.exception.ServiceException;
import com.sayimo.maker.commons.Constant;
import com.sayimo.maker.commons.utils.JSONUtil;
import com.sayimo.maker.mall.goods.dao.GoodsNormsValueStockInterfaceDao;
import com.sayimo.maker.mall.goods.dao.ShoppingCartInterfaceDao;
import com.sayimo.maker.mall.goods.dao.ShoppingCartNormsValueInterfacelDao;
import com.sayimo.maker.mall.goods.service.ShoppingCartService;
import com.sayimo.maker.mall.goods.vo.GoodsNormsValueStock;
import com.sayimo.maker.mall.goods.vo.ShoppingCart;
import com.sayimo.maker.mall.goods.vo.ShoppingCartNormsValue;
import com.sayimo.maker.mall.orders.service.OrdersListInterfaceService;


/**
 * @Copyright (c) 2015 广东省尚一互联网有限公司
 * @Project: schoolmallapi
 * @ClassName: ShoppingCartServiceImpl
 * @Description: 购物车
 * @Author:	chenpy
 * @Date:	日期：2015年12月29日  时间：上午10:43:04
 * @Version 1.0.0
 */
@Service(value = "shoppingCartServiceImpl")
public class ShoppingCartServiceImpl implements ShoppingCartService {
		
	private static Log logger = LogFactory.getLog(ShoppingCartServiceImpl.class);
	
	@Autowired
	private ShoppingCartInterfaceDao shoppingCartInterfaceImplDao;
	
	@Autowired
	private ShoppingCartNormsValueInterfacelDao shoppingCartNormsValueInterfaceImplDao;
	
	@Autowired
	private GoodsNormsValueStockInterfaceDao goodsNormsValueStockInterfaceImplDao;
	
	@Autowired
	private OrdersListInterfaceService ordersListInterfaceService;
	
	/**
	 * 
	 * @MethodName addShoppingCart
	 * @Description 添加购物车
	 * 
	 * @author chenpy
	 * @date 2016年1月5日 下午3:40:02
	 * @param 
	 * @return Map
	 * @VERSION 1.0.0
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map addShoppingCart(HttpServletRequest request) throws ServiceException{
		Map resultMap = new HashMap();
		try {
			Map dataMap = new HashMap();
			
			String _paramNormsValueId = request.getParameter("normsValueId"), 
				   _paramGoodsId = request.getParameter("goodsId"), 
				   _paramCustomerId = request.getAttribute("customerId").toString(), 
				   _paramBuyNum = request.getParameter("buyNum"),
				   _mallType = request.getParameter("mallType");
			
			logger.info("normsValueId = " + _paramNormsValueId + ", goodsId = "
					+ _paramGoodsId + ", customerId = " + _paramCustomerId
					+ ", buyNum = " + _paramBuyNum + ", mallType =" + _mallType);
			if (StringUtils.isEmpty(_paramNormsValueId) || StringUtils.isEmpty(_paramGoodsId) 
					|| StringUtils.isEmpty(_paramCustomerId) || StringUtils.isEmpty(_paramBuyNum) || StringUtils.isEmpty(_mallType)) { // 参数错误
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
				return resultMap;
			}
			
			int normsId = Integer.parseInt(_paramNormsValueId);
			int goodsId = Integer.parseInt(_paramGoodsId);
			int customerId = Integer.parseInt(_paramCustomerId);
			int buyNum = Integer.parseInt(_paramBuyNum);
			int mallType = Integer.parseInt(_mallType);
			
			// 判断库存是否足够
			GoodsNormsValueStock goodsNormsValueStock = new GoodsNormsValueStock();
			goodsNormsValueStock.setGoodsId(goodsId);
			goodsNormsValueStock.setGoodsNormsValueId(normsId);
			goodsNormsValueStock = goodsNormsValueStockInterfaceImplDao.queryGoodsNormsValueStockByGoodsId(goodsNormsValueStock);
			// 库存不足
			if(goodsNormsValueStock.getStockNum() < 1 || goodsNormsValueStock.getStockNum() < buyNum){
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.GOODS_STOCK_LACK);
				return resultMap;
			}
			
			// 判断购物车中是否已存在该商品
			ShoppingCart shoppingCart = new ShoppingCart();
			shoppingCart.setGoodsNormsValueId(normsId);
			shoppingCart.setGoodsId(goodsId);
			shoppingCart.setCustomerId(customerId);
			shoppingCart.setMallType(mallType);
			shoppingCart = shoppingCartInterfaceImplDao.queryShoppingCartByGoodsId(shoppingCart);
			
			if (shoppingCart != null) { // 购物车已存在该规格商品
				shoppingCart.setBuyNum(shoppingCart.getBuyNum() + buyNum);
				int num = shoppingCartInterfaceImplDao.updateShoppingCartById(shoppingCart);
				if (num > 0) {
					resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
					dataMap.put(Constant.MSG, "添加成功");
					resultMap.put(Constant.DATA, dataMap);
					return resultMap;
				}
				
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				dataMap.put(Constant.MSG, "添加失败");
				resultMap.put(Constant.DATA, dataMap);
				return resultMap;
			}
			else{ // 购物车不存在该商品
				shoppingCart = new ShoppingCart();
				shoppingCart.setCustomerId(customerId);
				shoppingCart.setBuyNum(buyNum);
				shoppingCart.setMallType(mallType);
				int num = shoppingCartInterfaceImplDao.insertShoppingCart(shoppingCart);
				if (num < 0) {
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
					dataMap.put(Constant.MSG, "添加失败");
					resultMap.put(Constant.DATA, dataMap);
					return resultMap;
				}
				
				ShoppingCartNormsValue cartNormsValue = new ShoppingCartNormsValue();
				cartNormsValue.setGoodsId(goodsId);
				cartNormsValue.setNormsValueId(normsId);
				cartNormsValue.setCartId(shoppingCart.getId());
				num = shoppingCartNormsValueInterfaceImplDao.insertShoppingCartNormsValue(cartNormsValue);
				if (num < 0) {
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
					dataMap.put(Constant.MSG, "添加失败");
					resultMap.put(Constant.DATA, dataMap);
					return resultMap;
				}
				
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				dataMap.put(Constant.MSG, "添加成功");
				resultMap.put(Constant.DATA, dataMap);
				return resultMap;
			}
		} catch (Exception e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 
	 * @MethodName deleteShoppingCarts
	 * @Description 删除购物车
	 * 
	 * @author chenpy
	 * @date 2016年1月5日 下午3:40:02
	 * @param 
	 * @return Map
	 * @VERSION 1.0.0
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map deleteShoppingCarts(HttpServletRequest request) throws ServiceException{
		Map resultMap = new HashMap();
		String shoppingCartId = request.getParameter("shoppingCartIds");
		try {
			Map dataMap = new HashMap();
			if (StringUtils.isEmpty(shoppingCartId)) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR, Constant.SYSTEM_REQUEST_PARAM_ERROR);
				return resultMap;
			}
			
			Integer cartId = Integer.parseInt(shoppingCartId);
			int num = shoppingCartNormsValueInterfaceImplDao.deleteShoppingCartByCartId(cartId);
			if (num < 0) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR, Constant.SYSTEM_ERROR);
				return resultMap;
			}
			
			num = shoppingCartInterfaceImplDao.deleteShoppingCartByCartId(cartId);
			if (num < 0) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR, Constant.SYSTEM_ERROR);
				return resultMap;
			}
			
			dataMap.put(Constant.MSG, "删除成功");
			resultMap.put(Constant.DATA, dataMap);
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			return resultMap;
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 
	 * @MethodName getShoppingCartList
	 * @Description 查看购物车
	 * 
	 * @author chenpy
	 * @date 2016年1月5日 下午6:40:35
	 * @param 
	 * @return Map
	 * @VERSION 1.0.0
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map getShoppingCartList(Integer customerId,Integer mallType) throws ServiceException {
		Map resultMap = new HashMap();
		try {
			Map tempMap=new HashMap();
			List<Map> list=new ArrayList<Map>(); 
			List<Map> providerList=shoppingCartInterfaceImplDao.getShoppingCartGoodsProviders(customerId,mallType);
			if(providerList!=null && providerList.size()>=0){
				if(providerList.size()==0){
					tempMap.put("shoppingCartList", list);
					tempMap.put("totalMoney", new BigDecimal(0));
					resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
					resultMap.put(Constant.DATA, tempMap);
					return resultMap;
				}else{
					BigDecimal totalMoney = new BigDecimal(0);
					for(Map map:providerList){
						
						List<ShoppingCart> carts = shoppingCartInterfaceImplDao.getShoppingCartList(customerId,(Integer)map.get("providerId"),mallType);
						JSONObject dataObject = new JSONObject();
						JSONArray shoppingCartArray = new JSONArray();
						
						for (ShoppingCart shoppingCart : carts) {
							JSONObject shoppingCartObject = new JSONObject();
							shoppingCartObject.put("shoppingCardId", shoppingCart.getId());
							shoppingCartObject.put("goodsName", shoppingCart.getGoodsName());
							shoppingCartObject.put("goodsStockCount", shoppingCart.getGoodsStockCount());
							shoppingCartObject.put("originalPrice", shoppingCart.getOriginalPrice());
							shoppingCartObject.put("salePrice", shoppingCart.getPreferentialPrice());
							shoppingCartObject.put("sellNum", shoppingCart.getBuyCountPeople());
							shoppingCartObject.put("normsValueId", shoppingCart.getGoodsNormsValueId());
							logger.info("normsValueIds = " + shoppingCart.getNormsValueIds());
							shoppingCartObject.put("normsValues", ordersListInterfaceService.getNormsValueString(shoppingCart.getNormsValueIds()));
							shoppingCartObject.put("buyNum", shoppingCart.getBuyNum());
							shoppingCartObject.put("photoUrl", shoppingCart.getPhotoUrl());
							shoppingCartObject.put("id", shoppingCart.getGoodsId());
							
							totalMoney = totalMoney.add(shoppingCart.getPreferentialPrice().multiply(new BigDecimal(shoppingCart.getBuyNum())));
							
							shoppingCartArray.put(shoppingCartObject);
						}
						
						dataObject.put("goodsList", shoppingCartArray);
						dataObject.put("providerName", map.get("providerName"));
						dataObject.put("providerId", map.get("id"));
						list.add(JSONUtil.readValueToMap(dataObject.toString()));
					}
					tempMap.put("shoppingCartList", list);
					tempMap.put("totalMoney", totalMoney);
					logger.info("shoppingCartList = " + JSONUtil.writeValueAsString(list));
					resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
					resultMap.put(Constant.DATA, tempMap);
					return resultMap;
				}
			}else{
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SELECT_ERROR);
				return resultMap;
			}
			
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
		
	}

	public ShoppingCartInterfaceDao getShoppingCartInterfaceImplDao() {
		return shoppingCartInterfaceImplDao;
	}

	public void setShoppingCartInterfaceImplDao(ShoppingCartInterfaceDao shoppingCartInterfaceImplDao) {
		this.shoppingCartInterfaceImplDao = shoppingCartInterfaceImplDao;
	}

	public ShoppingCartNormsValueInterfacelDao getShoppingCartNormsValueInterfaceImplDao() {
		return shoppingCartNormsValueInterfaceImplDao;
	}

	public void setShoppingCartNormsValueInterfaceImplDao(
			ShoppingCartNormsValueInterfacelDao shoppingCartNormsValueInterfaceImplDao) {
		this.shoppingCartNormsValueInterfaceImplDao = shoppingCartNormsValueInterfaceImplDao;
	}

	public GoodsNormsValueStockInterfaceDao getGoodsNormsValueStockInterfaceImplDao() {
		return goodsNormsValueStockInterfaceImplDao;
	}

	public void setGoodsNormsValueStockInterfaceImplDao(
			GoodsNormsValueStockInterfaceDao goodsNormsValueStockInterfaceImplDao) {
		this.goodsNormsValueStockInterfaceImplDao = goodsNormsValueStockInterfaceImplDao;
	}

	@Override
	public ShoppingCartNormsValue queryShoppingCartByCartId(Integer cartId,Integer customerId) throws ServiceException {
		try {
			Map<String, Object> parmMap = new HashMap<String, Object>();
			parmMap.put("cartId", cartId);
			parmMap.put("customerId", customerId);
			return shoppingCartNormsValueInterfaceImplDao.queryShoppingCartByCartId(parmMap);
		} catch (DaoException de) {
			throw new ServiceException(de);
		}
	}

	@Override
	public int deleteShoppingCartByIds(List<Integer> ids) throws ServiceException {
		try{
			return shoppingCartInterfaceImplDao.batchDeleteShoppingCartByIds(ids);
		}catch(DaoException de){
			throw new ServiceException(de);
		}
	}



}
